import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Tabs,
  Space,
  Button,
  Form,
  Row,
  Col,
  Input,
  message,
  Select,
  DatePicker,
  Checkbox,
  notification,
  Modal,
  Table,
} from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import {
  PlusOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  CheckOutlined,
  PrinterOutlined,
  ImportOutlined,
} from '@ant-design/icons';
import RcvDtlPo from './components/rcvDtlPo';
import request from '@/utils/request';
import moment from 'moment';
import { EmpSelect } from '@/components/FormItemSelect';
import PrintModal from '@/components/PrintModal';
import TempleteRcv from '../PrintTemplete/TempleteRcv';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';
import CateComp from '@/components/CategoryComponent';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/RcvHead/';
const apiURLDtl = '/api/services/app/RcvDtl/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState<any>({
    data: { packSlip: '0', id: '0' },
    details: [],
  });
  const [defTab, setDefTab] = useState('1');
  const [freshNum, setFreshNum] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [record, setRecord] = useState(null);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [selectedPORows, setSelectedPORows] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    formRef?.current?.setFieldsValue({ RcvHead: data });
  }, [data]);

  const onFinish = (values: { RcvHead: any }) => {
    if (defTab === '1') {
      save(values.RcvHead);
    }
  };

  const resetForm = () => {
    const data = {
      data: { packSlip: '0', id: '0' },
      details: [],
    };
    formRef.current.resetFields();
    formRef.current.setFieldsValue({ RcvHead: data.data });
    setData(data);
  };

  const save = (model: {
    receiptDate: { format: (arg0: string) => any };
    entryDate: { format: (arg0: string) => any };
    id: string | undefined;
  }) => {
    if (model.receiptDate) model.receiptDate = model.receiptDate.format('YYYY-MM-DD');
    if (model.entryDate) model.entryDate = model.entryDate.format('YYYY-MM-DD');
    let act = 'Modify';
    const method = 'POST';
    if (model.id === '0') {
      act = 'New';
      model.id = undefined;
    }
    setLoading(true);
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          if (response.result.success) {
            message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
            const RcvHead = response.result.data;
            if (RcvHead.receiptDate) RcvHead.receiptDate = moment(RcvHead.receiptDate);
            if (RcvHead.entryDate) RcvHead.entryDate = moment(RcvHead.entryDate);
            formRef.current.setFieldsValue({ RcvHead });
            setFreshNum(freshNum + 1);
            getObj(RcvHead.packSlip);
          } else {
            notification.error({
              message: 'Error',
              description: response.result.message,
            });
          }
        }
        setLoading(false);
      }
    });
  };

  const tabSwitch = (key: React.SetStateAction<string>) => {
    setDefTab(key);
  };

  const getObj = (value: string) => {
    if (!value) {
      return;
    }
    setLoading(true);
    request(apiURL + 'GetByNum', {
      method: 'GET',
      params: { num: value },
    }).then((response) => {
      if (response) {
        if (response.success) {
          const result = response.result;
          const RcvHead = result.data;
          if (RcvHead) {
            if (RcvHead.receiptDate) RcvHead.receiptDate = moment(RcvHead.receiptDate);
            if (RcvHead.entryDate) RcvHead.entryDate = moment(RcvHead.entryDate);
            formRef.current.setFieldsValue({ RcvHead });
            setData(result);
            setVisible(false);
            setLoading(false);
          }
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    if (data.data) {
      confirm({
        title: intl.formatMessage({ id: 'pages.warning' }),
        icon: <ExclamationCircleOutlined />,
        content: intl.formatMessage({ id: 'pages.delete.confirm' }),
        onOk() {
          request(apiURL + 'DelBatch', {
            method: 'POST',
            data: [data.data.id],
          }).then(() => {
            setFreshNum(freshNum + 1);
            resetForm();
          });
        },
      });
    }
  };

  const switchModal = (
    visible: boolean | ((prevState: boolean) => boolean),
    record: any = null,
  ) => {
    if (record == null) {
      record = {
        packSlip: data.data.packSlip,
        receiptType: data.data.receiptType,
        inspectionReq: true,
        warehouseCode: 'DJK',
        binNum: '1',
      };
    }
    setVisible(visible);
    setRecord(record);
  };

  const switchModal2 = (
    visible: boolean | ((prevState: boolean) => boolean),
    record: any = null,
  ) => {
    if (record == null) {
      record = {
        packSlip: data.data.packSlip,
        receiptType: data.data.receiptType,
        inspectionReq: true,
        warehouseCode: 'DJK',
        binNum: '1',
      };
    }
    setVisible3(visible);
    setRecord(record);
  };

  const delDtl = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURLDtl + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys,
        }).then(() => {
          getObj(data.data.packSlip);
          setFreshNum(freshNum + 1);
        });
      },
    });
  };

  const completeDtl = () => {
    const arrs: any = [];
    const lists = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) >= 0);
    lists.forEach((item: any) => {
      arrs.push({
        packSlip: item.packSlip,
        packLine: item.packLine,
      });
    });
    request(apiURLDtl + 'Complete', {
      method: 'POST',
      data: arrs,
    }).then((response) => {
      if (response.success) {
        const result = response.result;
        if (result.success) {
          message.success(intl.formatMessage({ id: 'pages.pick.success' }));
          getObj(arrs[0].packSlip);
        } else {
          message.error(result.message);
        }
      }
    });
  };

  const handlePrint = () => {
    setVisible2(true);
  };

  const handlePatchRcv = () => {
    const rcvHed = data.data;
    let i = data.details?.length + 1;
    selectedPORows.forEach((element: any) => {
      const obj = {
        warehouseCode: 'DJK',
        binNum: '1',
        poNum: element.PONum,
        poLine: element.POLine,
        poRelNum: element.PORelNum,
        vendorUnitCost: element.UnitCost,
        ium: element.IUM,
        inspectionReq: true,
        ourQty: element.RelQty,
        packSlip: rcvHed.packSlip,
        packLine: i,
        partNum: element.PartNum,
        partDescription: element.PartDescription,
        receiptType: rcvHed.receiptType,
      };
      handleRcv(obj);
      i++;
    });
    getObj(rcvHed.packSlip);
    setVisible3(false);
  };

  const handleRcv = (model: {
    warehouseCode: string;
    binNum: string;
    poNum: any;
    poLine: any;
    poRelNum: any;
    vendorUnitCost: any;
    ium: any;
    inspectionReq: boolean;
    ourQty: any;
    packSlip: string;
    packLine: number;
    partNum: any;
    partDescription: any;
    receiptType: any;
  }) => {
    setLoading(true);
    request('/api/services/app/RcvDtl/Create', {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          setLoading(false);
        }
      }
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.packSlip" />,
      dataIndex: 'packSlip',
      width: 200,
    },
    {
      title: <FormattedMessage id="pages.packLine" />,
      dataIndex: 'packLine',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'ourQty',
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.poNum" />,
      dataIndex: 'poNum',
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.complete" />,
      dataIndex: 'receivedComplete',
      key: 'receivedComplete',
      width: 80,
      render: (text: boolean | undefined) => <Checkbox checked={text} />,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (items: React.SetStateAction<any[]>) => {
      setSelectedRowKeys(items);
    },
  };

  const rowSelection2 = {
    onChange: (_selectedKeys: any, selectedRows: React.SetStateAction<never[]>) => {
      setSelectedPORows(selectedRows);
    },
  };

  const disabled = data?.data == undefined || data?.data?.received;

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={<FormattedMessage id="menu.part.rcvEntry" />}
          extra={
            <Space>
              <Button key="1" type="primary" icon={<PlusOutlined />} onClick={resetForm}>
                <span>
                  <FormattedMessage id="pages.reset" />
                </span>
              </Button>
              <Button
                key="2"
                type="primary"
                htmlType="submit"
                loading={loading}
                disabled={disabled}
              >
                <span>
                  <FormattedMessage id="pages.save" />
                </span>
              </Button>
              <Button
                key="4"
                type="dashed"
                danger
                icon={<CloseOutlined />}
                onClick={delObj}
                disabled={disabled || data.data?.id == '0'}
              >
                <span>
                  <FormattedMessage id="pages.delete" />
                </span>
              </Button>
              <Button key="5" type="ghost" icon={<PrinterOutlined />} onClick={handlePrint}>
                <span>
                  <FormattedMessage id="pages.print" />
                </span>
              </Button>
              <QuickMenu path="/part/rcvEntry" icon="icon-add_database" title="pages.RcvEntry" />
            </Space>
          }
        >
          <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
            <TabPane tab={<FormattedMessage id="pages.summary" />} key="1">
              <Row>
                <Col span={12}>
                  <Form.Item name={['RcvHead', 'id']} hidden={true}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['RcvHead', 'packSlip']}
                    label={<FormattedMessage id="pages.packSlip" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.packSlip.required" /> },
                    ]}
                  >
                    <Input style={{ width: 200 }} onBlur={(e) => getObj(e.target.value)} disabled />
                  </Form.Item>
                  <Form.Item
                    name={['RcvHead', 'receiptDate']}
                    label={<FormattedMessage id="pages.receiptDate" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.receiptDate.required" /> },
                    ]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <CateComp
                    layout="ReceiptType"
                    width={200}
                    name={['RcvHead', 'receiptType']}
                    label={<FormattedMessage id="pages.receiptType" />}
                    required
                    cateEditDisable
                  />
                  <EmpSelect
                    showSearch
                    width={200}
                    name={['RcvHead', 'receivePerson']}
                    label={<FormattedMessage id="pages.receivePerson" />}
                    params={{ deptCode: 'WD' }}
                  />
                </Col>
                <Col span={12}>
                  <Form.Item
                    name={['RcvHead', 'entryDate']}
                    label={<FormattedMessage id="pages.entryDate" />}
                  >
                    <DatePicker />
                  </Form.Item>
                  <Form.Item
                    name={['RcvHead', 'receiptComment']}
                    label={<FormattedMessage id="pages.commentText" />}
                  >
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 5 }}>
                    <Input.Group compact>
                      <Form.Item name={['RcvHead', 'received']} valuePropName="checked">
                        <Checkbox disabled>
                          <FormattedMessage id="pages.received" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['RcvHead', 'invoiced']} valuePropName="checked">
                        <Checkbox disabled>
                          <FormattedMessage id="pages.invoiced" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.rcvDetail" />} key="2">
              <Table
                rowKey="id"
                size="small"
                columns={columns}
                loading={loading}
                dataSource={data.details}
                rowSelection={rowSelection}
                onRow={(obj) => {
                  return {
                    onDoubleClick: () => {
                      switchModal(true, obj);
                    },
                  };
                }}
                footer={() => (
                  <Space>
                    <Button
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={() => switchModal(true)}
                      disabled={disabled}
                    >
                      <span>
                        <FormattedMessage id="pages.newDetail" />
                      </span>
                    </Button>
                    <Button
                      block
                      type="ghost"
                      icon={<ImportOutlined />}
                      onClick={() => switchModal2(true)}
                      disabled={disabled}
                    >
                      <span>
                        <FormattedMessage id="pages.rcvBatch" />
                      </span>
                    </Button>
                    <Button
                      type="default"
                      icon={<CheckOutlined />}
                      onClick={completeDtl}
                      disabled={selectedRowKeys.length <= 0 || disabled}
                    >
                      <span>
                        <FormattedMessage id="pages.receiveAll" />
                      </span>
                    </Button>
                    <Button
                      type="dashed"
                      danger
                      icon={<CloseOutlined />}
                      onClick={delDtl}
                      disabled={selectedRowKeys.length <= 0 || disabled}
                    >
                      <span>
                        <FormattedMessage id="pages.delete" />
                      </span>
                    </Button>
                  </Space>
                )}
              />
            </TabPane>
          </Tabs>
        </Card>
      </Form>
      <OperpQuery
        sysReportName="ReportRcv"
        scroll={{ x: 'max-content', y: '200px' }}
        freshNum={freshNum}
        callback={(e) => getObj(e.PackSlip)}
      />
      <Modal
        title={<FormattedMessage id="pages.rcvDetail" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => switchModal(false)}
        footer={false}
      >
        <RcvDtlPo onRef={setRecord} data={record} refreshData={getObj} />
      </Modal>
      <Modal
        title={<FormattedMessage id="pages.shipBatch" />}
        visible={visible3}
        destroyOnClose={true}
        onCancel={() => switchModal2(false)}
        footer={
          <Button type="primary" onClick={handlePatchRcv}>
            <FormattedMessage id="submit" />
          </Button>
        }
        width={880}
        bodyStyle={{ padding: '0px' }}
      >
        <OperpQuery
          sysReportName="ReportPORel"
          scroll={{ x: 'max-content', y: '200px' }}
          search={{ filterType: 'light' }}
          rowSelection={rowSelection2}
          params={{ OpenOrder: 1, Approve: 1, ApprovalStatus: 'A' }}
        />
      </Modal>
      <Modal
        width={1024}
        title={<FormattedMessage id="pages.print" />}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <PrintModal>
          <TempleteRcv data={data} configData={props.currentConfig} />
        </PrintModal>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
  currentConfig: user.currentConfig,
}))(ViewPage);
